// slbModel.go
package models

import (
	"errors"
	//"fmt"

	"fmt"
	"log"

	//"time"

	//"strconv"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/validation"
)

type Limitrule struct {
	Id             int64   `json:"id"`
	Appname        string  `json:"appname" valid:"Required"`
	Limit_host     string  `json:"limit_host"`
	Limit_url      string  `json:"limit_url" valid:"Required"`
	Limit_type     string  `json:"limit_type"`
	Limit_key      string  `json:"limit_key"`
	Limit_rate     float64 `json:"limit_rate"`
	Limit_speed    bool    `json:"limit_speed"`
	Limit_enable   bool    `json:"limit_enable"`
	Limit_priority int     `json:"limit_priority"`
	Limit_downrate int64   `json:"limit_downrate"`
	Remarks        string  `json:"remarks"`
	Updatetime     string  `json:"updatetime"`
	Createtime     string  `json:"createtime"`
}

func init() {
	orm.Debug = true
	//orm.RegisterModel(new(Limitrule)) //因为configModel中已注册，无法重复注册，即使更改结构体名称
}

func (u *Limitrule) TableName() string {
	return "xf_reqlimit_rule"
}

func check_xlr(u *Limitrule) (err error) {
	valid := validation.Validation{}
	b, _ := valid.Valid(&u)
	if !b {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
			return errors.New(err.Message)
		}
	}
	return nil
}

//List
func GetXf_reqlimit_rule(appname string, id int64) (xlr []*Limitrule, count int64) {
	o := orm.NewOrm()
	var sqlstr string
	if id > 0 {
		sqlstr = fmt.Sprintf("select * from xf_reqlimit_rule where id = '%d'", id)
	}
	if appname != "" {
		sqlstr = fmt.Sprintf("select * from xf_reqlimit_rule where appname = '%s' ORDER BY limit_priority,limit_host desc,limit_url desc, CONVERT(limit_rate,signed)", appname)
	}
	num, err2 := o.Raw(sqlstr).QueryRows(&xlr)
	if err2 != nil {
		log.Println(err2)
	}
	return xlr, num
}

//添加
func AddXf_reqlimit_rule(u *Limitrule) (int64, error) {
	if err := check_xlr(u); err != nil {
		return 0, err
	}
	o := orm.NewOrm()
	var numt int64
	res, err := o.Raw(`insert into xf_reqlimit_rule(appname,limit_host,limit_url,limit_type, limit_key,limit_rate,remarks)values(?,?,?,?,?,?,?)`, u.Appname, u.Limit_host, u.Limit_url, u.Limit_type, u.Limit_key, u.Limit_rate, u.Remarks).Exec()
	if err != nil {
		log.Printf("[ERROR] Add LimitRule err:%s\n", err)
		return 0, err
	}
	Id, _ := res.LastInsertId()
	if Id > 0 {
		numt++
	}
	UpdateConfigTime(u.Appname)
	return numt, nil
}

func DelLimitRuleById(id int64, appname string) (int64, error) {
	o := orm.NewOrm()
	res, err := o.Raw(`DELETE FROM xf_reqlimit_rule WHERE id = ?`, id).Exec()
	if err != nil {
		log.Printf("[ERROR] Del LimitRule err:%s\n", err)
		return 0, err
	}
	num, err := res.RowsAffected()
	if err != nil {
		log.Printf("[ERROR] Del customurlFail3 err:%s\n", err)
		return 0, err
	}
	UpdateConfigTime(appname)
	return num, nil
}

func EditLimitRule(id, appname, key, value string) (int64, error) {
	o := orm.NewOrm()
	sqlstr := fmt.Sprintf("UPDATE xf_reqlimit_rule SET %s = '%s' WHERE id = %s AND appname = '%s'", key, value, id, appname)
	res, err := o.Raw(sqlstr).Exec()
	if err == nil {
		num, _ := res.RowsAffected()
		log.Printf("[INFO] EditLimitRule affected nums:%d\n", num)
		UpdateConfigTime(appname)
		return num, nil
	}
	return 0, err
}
